﻿#region Copyright (C) Sector7 Software Studio. All rights reserved
/*******************************************************************************************
 * Creation
 *      Author:         Wolf Lai
 *      Date:           2011/10/27 21:48:54
 *      Version:        1.0.1101
 * Modification 
 *      Author: 
 *      Date: 
 *      Description: 
 *      Version:
 *******************************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sector7.Framework.Utility
{
    /// <summary>
    /// 字符串工具类
    /// </summary>
    public class StringUtil
    {
        #region Public functions
        /// <summary>
        /// 字符串转换成byte数组
        /// </summary>
        /// <param name="source">字符串值</param>
        /// <returns></returns>
        public static byte[] StringToBytes(string source)
        {
            byte[] array = StringToBytes(source, Encoding.UTF8);
            return array;
        }

        /// <summary>
        /// 字符串转换成byte数组
        /// </summary>
        /// <param name="source">字符串值</param>
        /// <param name="encoding">字符编码</param>
        /// <returns></returns>
        public static byte[] StringToBytes(string source, Encoding encoding)
        {
            byte[] array = encoding.GetBytes(source);
            return array;
        }

        /// <summary>
        /// byte数组转换成字符串（截取'\0'）
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <returns>字符串</returns>
        public static string BytesToString(byte[] bytes)
        {
            string retVal = BytesToString(bytes, Encoding.UTF8);
            return retVal;
        }

        /// <summary>
        /// byte数组转换成字符串（截取'\0'）
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <param name="encoding">字符编码类型</param>
        /// <returns>字符串</returns>
        public static string BytesToString(byte[] bytes, Encoding encoding)
        {
            string retVal = encoding.GetString(bytes).Replace('\0', ' ').Trim();
            return retVal;
        }

        /// <summary>
        /// byte指针转换成字符串（截取'\0'）
        /// </summary>
        /// <param name="pointer">byte指针</param>
        /// <param name="length">指针长度</param>
        /// <returns>字符串</returns>
        public static unsafe string PointToString(byte* pointer, int length)
        {
            string retVal = string.Empty;
            byte[] temp = new byte[length];
            bool isFill = false;

            for (int i = 0; i < length; i++)
            {
                byte b = pointer[i];
                temp[i] = b;

                if (isFill)
                {
                    temp[i] = 0;
                }
                else
                {
                    if (b == 0)
                        isFill = true;
                }
            }
            retVal = BytesToString(temp);
            return retVal;
        }

        /// <summary>
        /// byte指针转换成字符串（截取'\0'）
        /// </summary>
        /// <param name="pointer">byte指针</param>
        /// <param name="length">指针长度</param>
        /// <param name="encoding">字符编码类型</param>
        /// <returns>字符串</returns>
        public static unsafe string PointToString(byte* pointer, int length, Encoding encoding)
        {
            string retVal = string.Empty;
            byte[] temp = new byte[length];
            for (int i = 0; i < length; i++)
            {
                temp[i] = pointer[i];
            }
            retVal = BytesToString(temp, encoding);
            return retVal;
        }

        /// <summary>
        /// byte指针转换成字符串（截取'\0'）
        /// </summary>
        /// <param name="pointer">byte指针</param>
        /// <returns>字符串</returns>
        public static unsafe string PointToString(byte* pointer)
        {
            string retVal = new string((char*)pointer);

            return retVal;
        }

        /// <summary>
        /// sbyte指针转换成字符串（截取'\0'）
        /// </summary>
        /// <param name="pointer">sbyte指针</param>
        /// <returns>字符串</returns>
        public static unsafe string PointToString(sbyte* pointer)
        {
            string retVal = new string(pointer);

            return retVal;
        }

        /// <summary>
        /// 右对齐此实例中的字符，在左边用 '0' 填充至2位。
        /// </summary>
        /// <param name="source">需要右对齐的对象</param>
        /// <returns>
        ///		等效于此实例的一个新 System.String，但它是右对齐的，并在左边用达到长度2所需数目的'0'进行填充。如果
        ///		totalWidth 小于此实例的长度，则为与此实例相同的新 System.String。
        ///	</returns>
        public static string PadLeft(object source)
        {
            if (source != null)
                return source.ToString().PadLeft(2, '0');
            else
                return string.Empty.PadLeft(2, '0');
        }

        /// <summary>
        /// 右对齐此实例中的字符，在左边用指定的 Unicode 字符填充以达到指定的总长度。
        /// </summary>
        /// <param name="source">需要右对齐的对象</param>
        /// <param name="totalWidth">结果字符串中的字符数，等于原始字符数加上任何其他填充字符。</param>
        /// <param name="paddingChar">Unicode 填充字符</param>
        /// <returns>
        ///		等效于此实例的一个新 System.String，但它是右对齐的，并在左边用达到 totalWidth 长度所需数目的 paddingChar 字符进行填充。如果
        ///		totalWidth 小于此实例的长度，则为与此实例相同的新 System.String。
        ///	</returns>
        public static string PadLeft(object source, int totalWidth, char paddingChar)
        {
            if (source != null)
                return source.ToString().PadLeft(totalWidth, paddingChar);
            else
                return string.Empty.PadLeft(totalWidth, paddingChar);
        }

        /// <summary>
        /// 字符串结束填充'\0'
        /// </summary>
        /// <param name="source">需要填充的对象</param>
        /// <returns></returns>
        public static byte[] PadEnd(string source)
        {
            int length = source.Length;

            byte[] temp = StringToBytes(source);
            byte[] array = new byte[length + 1];

            for (int i = 0; i < length; i++)
            {
                array[i] = temp[i];
            }
            array[length] = 0;

            return array;
        }

        /// <summary>
        /// 字符串结束填充指定内容（若以为指定内容，则不填充）
        /// </summary>
        /// <param name="source">需要填充的对象</param>
        /// <param name="padding">填充内容</param>
        /// <returns></returns>
        public static string PadEnd(string source, string padding)
        {
            if (!source.EndsWith(padding))
                source += padding;

            return source;
        }

        /// <summary>
        /// 根据指定字符串格式，从源字符串中摘取子字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="format">字符串格式，形如：{0}.{1}.{0}</param>
        /// <returns>摘取的子字符串数组</returns>
        public static List<string> ExtractString(string source, string format)
        {
            List<string> subStrings = new List<string>();

            int start = 0;
            int stop = 0;
            string __source = source;
            string subString = string.Empty;
            char mark;
            while (format.Length > 0)
            {
                start = format.IndexOf('{');
                stop = format.IndexOf('}');

                if (start >= 0 && stop >= 0)
                {
                    stop++;

                    if (stop < format.Length)
                    {
                        mark = format[stop];

                        stop++;
                        if (stop < format.Length)
                        {
                            format = format.Substring(stop);
                        }
                        else
                        {
                            format = string.Empty;
                        }

                        __source = __source.Substring(start);
                        stop = __source.IndexOf(mark);

                        subString = __source.Substring(0, stop);

                        stop++;
                        __source = __source.Substring(stop);
                    }
                    else
                    {
                        subString = __source.Substring(start);
                        format = string.Empty;
                    }

                    subStrings.Add(subString);
                }
            }

            return subStrings;
        }
        #endregion
    }
}
